﻿using GJXQGame;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public sealed class ResourcesManager
{
    public const string RootPathResourcesTexturesGacha = "Textures/Gacha/";
    private static ResourcesManager m_cInstance; //实例

    public static ResourcesManager GetInstance()
    {
        if (m_cInstance == null)
        {
            m_cInstance = new ResourcesManager();
        }

        return m_cInstance;
    }
    public TextAsset LoadTextAsset(string path)
    {
        TextAsset textAsset = Resources.Load<TextAsset>(path);
        return textAsset;
    }
    private static int _retry_times = 0;
    private const float RETRY_LAG = 30;
    private static float _download_progress = 0;

    public static IEnumerator CoroutineLoad(string url, Action<WWW> action = null)
    {
        WWW www = new WWW(url);
        float time_start = Time.time;
        _retry_times = 0;
        while (!www.isDone)
        {
            if (Time.time - time_start > RETRY_LAG)
            {
                if (_retry_times == 0)
                {
                    _download_progress = www.progress;
                    Debug.LogError("[DOWNLOAD]first retry: " + url + ", progress: " + _download_progress);
                    time_start = Time.time;
                    _retry_times++;
                    continue;
                }

                if (_download_progress == www.progress)
                {
                    if (_retry_times > 1)
                    {
                        Debug.LogError("[DOWNLOAD]download failed: " + url + ", progress: " + _download_progress);
                        www.Dispose();
                        yield break;
                    }

                    www.InitWWW(url, null, null);
                    time_start = Time.time;
                    _retry_times++;
                    continue;
                }

                _retry_times = 0;
            }
            yield return null;
        }
        yield return www;

        if (action != null) action(www);
        www.Dispose();
    }
    public GameObject InstantiateGameObject(string prefPath)
    {
        GameObject go = null;
        try
        {
            go = GameObject.Instantiate(Resources.Load(prefPath)) as GameObject;
        }
        catch
        {
            GameLog.LogError("InstantiateGameObject error:" + prefPath);
        }
        return go;
    }
}
